<template>
  <!-- 发料价格调整 -->
  <div>
    <!-- 顶部提示框 -->
    <FormPanel ref="topForm" :list="topForm" :cols="4" :collapse="false" :isSubmitBtn="false"></FormPanel>
    <!-- 详情面板 -->
    <div style="margin-bottom: 15px;color: red;">
      <p>友情提示：黄色为配件销售价小于成本价</p>
    </div>
    <FilterTable
      ref="table"
      height="350"
      columnsRef="partInventoryManagerPatrItemAdjustIndex"
      :columns="tableColumns"
      :isMemoryPagination="true"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :dataSource="tableDataSource"
      :onColumnsChange="columns => (this.tableColumns = columns)"
      :onCellChange="tableCellChange"
      :rowstyles="styleList"
      :onSyncTableData="syncDataChange"
    >
      <template slot="controls">
        <el-button type="primary" :loading="saveBtnLoading" :disabled="saveBtnDisabled" @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handleCancle">取消</el-button>
      </template>
    </FilterTable>
    <!-- 操作按钮 -->
    <!-- <el-button type="primary" icon="el-icon-circle-plus-outline" :loading="saveBtnLoading" :disabled="saveBtnDisabled" @click="handleSave">保存</el-button>
      <el-button type="primary" icon="el-icon-refresh-right" @click="handleCancle">取消</el-button> -->
    <!-- 工单选择框 -->
    <BaseDialog :visible.sync="workeOrderSelectVisible" title="选择工单" :destroyOnClose="true" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <WorkOrderSelect :workOrderCode="workOrderCode" @changeWorkOrderSelectDialog="changeWorkOrderSelectDialog" @onConfirm="workOrderOnConfirm"></WorkOrderSelect>
    </BaseDialog>
    <!-- 车牌选择框 -->
    <BaseDialog :visible.sync="licenceSelectVisible" title="选择车牌" :destroyOnClose="true" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <LicenseSelect :licenseNo="licenseNo" @onConfirm="handleLicenseConfirm" @closeDialog="changeLicenceSelectVisible"></LicenseSelect>
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { getAllModel } from '@/api/part/partInfo';
import { notifyAction } from '@/utils';
import { exportExcelFile, arrayObjDeWeight } from '@/utils/index';
import WorkOrderSelect from './WorkOrderSelect';
import LicenseSelect from './LicenseSelect';
import { queryTax } from '@/api/part/partOutbound/repairMaterials/index.js';
import { getPartCostAdjustDatas, updateOrderPartPrice } from '@/api/part/inventoryManager/partPriceAdjust';
import { getWorkOrderlist, getAllReparType } from '@/api/part/inventoryManager/partPriceAdjust';
import { queryUnitCode } from '@/api/part/partInfo';
import { getDealerUser } from '@/api/customerRepair/customerComplaint/customerComplaintReception';
export default {
  name: 'part_inventoryManager_patritemAdjust',
  components: { WorkOrderSelect, LicenseSelect },
  mixins: [dictionary],
  data() {
    return {
      // 页面查询api
      fetchApi: getPartCostAdjustDatas,
      fetchParams: { xhrAbort: true },
      workeOrderSelectVisible: false, // 是否显示工单选择框
      allRepairType: [], // 所有维修类型(回显用)
      licenceSelectVisible: false, // 是否显示车牌选择框
      topForm: this.createTopForm(),
      tableColumns: this.createTableColumns(),
      searchParams: {
        roNo: '',
        license: '',
        partNO: ''
      },
      tax: 0,
      workOrderCode: '', // 输入的工单号(弹窗默认查询条件)
      licenseNo: '', // 输入的车牌号
      tableList: [], // 列表数据
      submitData: {}, // 暂存修改数据(key为id value为修改后的数据)
      saveBtnLoading: false,
      saveBtnDisabled: true,
      styleList: [],
      allUserList: [], // 人员列表
      tableDataSource: [] // table表格数据源
    };
  },
  created() {},
  mounted() {
    this.queryAllRepairType();
    this.getAllUser();
    // this.queryUnitCode();
    // this.queryTax();
    this.getAllModel();
  },
  methods: {
    // 获取全部人员列表
    async getAllUser() {
      let res = await getDealerUser();
      // this.currentUserId = await getUserId();
      let data = arrayObjDeWeight(res.data, 'userId');
      this.allUserList = data.map(item => ({ text: item.employeeName, value: '' + item.userId }));
      console.log('ssss::', this.allUserList);
      this.setListItem();
    },
    createTopForm() {
      return [
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo',
          initialValue: '',
          readonly: true,
          placeholder: '请选择工单号',
          rules: [{ required: true, message: '请选择工单号', trigger: 'blur' }],
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.handleWorkOrderSearch}></el-button>;
          }
          // onEnter: val => {
          //   this.openWorkOrderSelectDialog();
          // }
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          placeholder: '请选择或输入车牌号',
          initialValue: '',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '维修类型',
          placeholder: '请输入维修类型',
          fieldName: 'repairTypeCode',
          itemList: [],
          disabled: true
        },
        {
          type: 'SELECT',
          label: '车型',
          placeholder: '请输入车型',
          fieldName: 'model',
          disabled: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          placeholder: '请输入服务顾问',
          fieldName: 'serviceAdvisor',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: 'VIN',
          placeholder: '请输入VIN',
          fieldName: 'vin',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主',
          placeholder: '请输入车主',
          fieldName: 'ownerName',
          disabled: true
        },
        {
          type: 'DATE',
          label: '开单日期',
          placeholder: '请输入开单日期',
          fieldName: 'roCreateDate',
          disabled: true,
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'SELECT',
          label: '责任技师',
          placeholder: '请输入责任技师',
          fieldName: 'chiefTechnician',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '排量',
          placeholder: '请输入排量',
          fieldName: 'engineDesc',
          disabled: true
        }
        // {
        //   type: 'INPUT',
        //   label: '税率',
        //   placeholder: '请输入税率',
        //   fieldName: 'tax',
        //   disabled: true
        // }
        // {
        //   type: 'INPUT',
        //   label: '车主',
        //   placeholder: ' 请先选择工单号',
        //   disabled: true,
        //   initialValue: ''
        // },
        // {
        //   type: 'INPUT',
        //   label: '车型',
        //   placeholder: ' 请先选择工单号',
        //   disabled: true,
        //   initialValue: ''
        // },
        // {
        //   type: 'INPUT',
        //   label: '服务专员',
        //   placeholder: ' 请先选择工单号',
        //   disabled: true,
        //   initialValue: ''
        // },
        // {
        //   type: 'INPUT',
        //   label: '开单日期',
        //   placeholder: ' 请先选择工单号',
        //   disabled: true,
        //   initialValue: ''
        // },
        // {
        //   type: 'INPUT',
        //   label: '维修类型',
        //   placeholder: ' 请先选择工单号',
        //   disabled: true,
        //   initialValue: ''
        // },
        // {
        //   type: 'INPUT',
        //   label: '指定技师',
        //   placeholder: ' 请先选择工单号',
        //   disabled: true,
        //   initialValue: ''
        // }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          sorter: true,
          dataIndex: 'customerIndex',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '仓库',
          dataIndex: 'storageName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '库位',
          dataIndex: 'storagePositionCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '原单价',
          dataIndex: 'partSalesPriceOld',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '配件含税销售单价',
          dataIndex: 'partSalesPrice',
          precision: 2,
          editable: true,
          editType: 'number',
          defaultEditable: true,
          // className: 'text_blue',
          sorter: true
          // filter: true,
          // filterType: 'input'
        },
        {
          title: '含税成本价',
          dataIndex: 'partCostPrice',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        // {
        //   title: '含税成本价',
        //   dataIndex: 'partCostTaxPrice',
        //   precision: 2,
        //   sorter: true,
        //   filter: true,
        //   filterType: 'number',
        //   render: props => {
        //     props.row.partCostTaxPrice = props.row.partCostPrice * (1 + this.tax);
        //     return <span>{props.row.partCostTaxPrice.toFixed(2)}</span>;
        //   }
        // },
        {
          title: '计量单位',
          dataIndex: 'unitName',
          filter: true,
          filterType: 'input'
        },
        {
          title: '数量',
          dataIndex: 'partQuantity',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '金额',
          dataIndex: 'partSalesAmount',
          precision: 2,
          summation: true,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '收费区分',
          dataIndex: 'chargePartitionName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '领料人',
          dataIndex: 'receiver',
          sorter: true,
          filterItems: this.allUserList,
          dictItems: []
        }
        // {
        //   title: '流水号',
        //   dataIndex: 'batchNo',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // }
      ];
    },
    async queryUnitCode() {
      const res3 = await queryUnitCode();
      this.tableColumns.find(item => item.dataIndex == 'unitCode').editItems = res3.data.map(x => ({ text: x.UNIT_NAME, value: x.UNIT_CODE }));
    },
    setListItem() {
      this.topForm.find(x => x.fieldName == 'serviceAdvisor').itemList = this.allUserList;
      this.topForm.find(x => x.fieldName == 'chiefTechnician').itemList = this.allUserList;
      this.tableColumns.find(x => x.dataIndex == 'receiver').dictItems = this.allUserList;
    },
    // 查询主页面列表
    async getTableList() {
      this.styleList = [];
      this.$refs.table.$refs.pageTable.START_LOADING();
      console.log(this.searchParams, 1111111111);
      try {
        let res = await getPartCostAdjustDatas(this.searchParams);
        this.$refs.table.$refs.pageTable.STOP_LOADING();
        if (res.resultCode == 200) {
          this.tableList = res.data;
        }
        // console.log(123123);
        // this.fetchParams = Object.assign({}, { xhrAbort: false }, this.searchParams);

        this.tableList.map(item => {
          item.partSalesPrice_old = item.partSalesPrice;
        });
        this.tableList.forEach(x => {
          if (x.partSalesPrice != null && x.partSalesPrice != undefined && x.partSalesPrice != '') {
            if (Number(x.partSalesPrice) < Number(x.partCostPrice)) {
              this.styleList.push({ row: x, styles: { backgroundColor: '#ffd200' } });
              // if (this.styleList.length > 0) {
              //   this.styleList.forEach((item, index) => {
              //     if (x.partNo != item.row.partNo) {
              //       this.styleList.push({ row: x, styles: { backgroundColor: '#ffd200' } });
              //     }
              //   });
              // } else {
              //   this.styleList.push({ row: x, styles: { backgroundColor: '#ffd200' } });
              // }
            }
          }
        });
        this.tableDataSource = this.tableList;
      } catch (err) {
        // console.log(err);
        this.$refs.table.$refs.pageTable.STOP_LOADING();
      }
      this.$refs.table.$refs.pageTable.STOP_LOADING();
    },
    // 点击工单号搜索图标
    async handleWorkOrderSearch(row) {
      // let params = await this.$refs.topForm.GET_FORM_DATA();
      // this.workOrderCode = params[1] && params[1].roNo ? params[1].roNo : null;
      this.changeWorkOrderSelectDialog(true);
    },
    // 工单号选择点击确定
    workOrderOnConfirm(e) {
      console.log(1231, e);

      this.topForm[0].initialValue = e.roNo;
      this.topForm[1].initialValue = e.license;
      this.topForm[2].initialValue = e.repairTypeCode;
      this.topForm[3].initialValue = e.model;
      this.topForm[4].initialValue = e.serviceAdvisor;
      this.topForm[5].initialValue = e.vin;
      this.topForm[6].initialValue = e.ownerName;
      this.topForm[7].initialValue = e.roCreateDate;
      this.topForm[8].initialValue = e.chiefTechnician;
      this.topForm[9].initialValue = e.engineDesc;
      // this.topForm[10].initialValue = e.tax;
      this.searchParams.roNo = e.roNo;
      this.getTableList();
    },
    // 点击车牌号搜索图标
    async handleLicenseNoSearch() {
      let params = await this.$refs.topForm.GET_FORM_DATA();
      this.licenseNo = params[1].license;
      this.changeLicenceSelectVisible(true);
    },
    // 车牌号搜索点击确定
    handleLicenseConfirm(e) {
      this.topForm[1].initialValue = e.roNo;
      this.searchParams.license = e.roNo;
      this.getTableList();
    },
    // 修改工单选择显示隐藏
    changeWorkOrderSelectDialog(val) {
      this.workeOrderSelectVisible = !!val;
    },
    // 修改车牌选择显示隐藏
    changeLicenceSelectVisible(val) {
      this.licenceSelectVisible = !!val;
    },
    // 点击顶部搜索或重置按钮
    handleTopFilterChange(e) {
      // console.log(e);
      let param = e;
      let flag = flag;
      for (let item in this.searchParams) {
        this.searchParams[item] = param[item];
        if (this.searchParams[item]) {
          flag = true;
        }
      }
      if (flag) {
        this.getTableList();
      } else {
        this.tableList = [];
      }
    },
    syncDataChange(val) {
      this.tableList = val;
    },
    // 表格内数据变化(修改价格)
    tableCellChange(e1, e2) {
      let keys = Object.keys(e1);
      this.saveBtnDisabled = !!!keys.length;
      let key = keys[0];
      this.submitData[e2.itemId] = e1[key];
      // val.forEach(x => {
      if (e2.partSalesPrice != null && e2.partSalesPrice != undefined && e2.partSalesPrice != '') {
        debugger;
        if (Number(e2.partSalesPrice) < Number(e2.partCostPrice)) {
          this.styleList.push({ row: e2, styles: { backgroundColor: '#ffd200' } });
          // if (this.styleList.length > 0) {
          //   this.styleList.forEach((item, index) => {
          //     if (e2.partNo != item.row.partNo) {
          //       this.styleList.push({ row: e2, styles: { backgroundColor: '#ffd200' } });
          //     }
          //   });
          // } else {
          //   this.styleList.push({ row: e2, styles: { backgroundColor: '#ffd200' } });
          // }
          console.log(this.styleList, 'this.styleList');
        } else {
          this.styleList.forEach((item, index) => {
            console.log(e2.itemId == item.row.itemId, 'e2.partNo == item.row.partNo');
            if (e2.itemId == item.row.itemId) {
              this.styleList.splice(index, 1);
              this.styleList = [...this.styleList];
            }
          });
        }
      }
      // let styleList = Array.from(new Set(this.styleList));
      // this.styleList = styleList;
      this.styleList = [...this.styleList];
      // });
    },
    async getAllModel() {
      let res = await getAllModel();
      this.topForm.find(x => x.fieldName == 'model').itemList = res.data.map(x => ({ text: x.MODEL_NAME, value: '' + x.MODEL_ID }));
    },
    // 点击取消按钮
    handleCancle() {
      this.$refs.topForm.RESET_FORM();
      this.styleList = [];
      this.tableDataSource = [];
    },
    // 获取税率
    async queryTax() {
      const res = await queryTax();
      if (res.resultCode == 200) {
        this.tax = Number(res.data) || 0;
      }
    },
    // 获取全部维修类型
    async queryAllRepairType() {
      let res = await getAllReparType();
      let obj = {};
      this.allRepairType = res.data.map(item => ({ text: item.REPAIR_TYPE_NAME, value: '' + item.REPAIR_TYPE_CODE }));
      this.topForm.find(x => x.fieldName == 'repairTypeCode').itemList = this.allRepairType;

      // res.data.map(item => {
      //   obj[item.REPAIR_TYPE_CODE] = item.REPAIR_TYPE_NAME;
      // });
      // obj.keys().forEach(x => {
      //   this.allRepairType.push({ text: obj[x], value: x });
      // });
    },
    changeHandle() {
      console.log('ccc');
      this.tableDataSource = [];
    },
    // 点击保存
    async handleSave() {
      if (!Object.keys(this.submitData).length) return;
      let flag = false;
      let arr = [];
      for (let item in this.submitData) {
        console.log('item.partSalesPrice:::', this.submitData[item]);
        if (!this.submitData[item] || this.submitData[item] == '') {
          flag = true;
        }
        arr.push({
          itemId: item,
          partSalesPrice: this.submitData[item]
        });
      }
      if (flag) {
        notifyAction('请输入销售单价', 'warning');
        return;
      }
      if (this.saveBtnLoading) return;
      this.saveBtnLoading = true;
      try {
        let res = await updateOrderPartPrice({
          roNo: this.topForm[0].initialValue,
          dtoList: arr
        });
        notifyAction('修改成功');
        this.saveBtnLoading = false;
        this.getTableList();
      } catch (err) {
        this.saveBtnLoading = false;
        console.log(err);
      }
    }
  }
};
</script>

<style>
.text_blue {
  color: blue !important;
}
.text_btn {
  text-align: center;
  position: relative;
  margin-top: 10px;
}
.test {
  position: absolute;
  left: 20px;
  top: 10px;
  color: red;
}
</style>
